﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using AnjLab.FX.Sys;
using AnjLab.SyncIT.Core.Api;
using Control=System.Windows.Forms.Control;

namespace AnjLab.SyncIT.App
{
    /// <summary>
    /// Interaction logic for SyncInfoWindow.xaml
    /// </summary>
    public partial class SyncInfoWindow : Window
    {
        private static readonly List<SyncInfoWindow> _stack = new List<SyncInfoWindow>();

        private static readonly object _syncObject = new object();
        readonly Timer _timer = new Timer();

        public SyncInfoWindow()
        {
            InitializeComponent();
            _timer.Interval = (int) TimeSpan.FromSeconds(3).TotalMilliseconds;
            _timer.Tick += _timer_Tick;
            _timer.Start();
            
            
        }

        public string IconSource { get; set; }

        void _timer_Tick(object sender, EventArgs e)
        {
            CloseWindow();
        }

        private void CloseWindow() {
            lock (_syncObject) {

                _stack.Remove(this);
                foreach (var window in _stack) {
                    if (window.Top < Top)
                        window.Top += window.Height;
                }
                
                _timer.Stop();
                Close();
            }
        }

        private void WindowMouse_Down(object sender, MouseButtonEventArgs e) {
            CloseWindow();
        }

        public static void ShowUpdated(EventArgs<Source, string> e) {
            var wnd = new SyncInfoWindow();

            wnd.IconSource = e.Item1.Icon;
            wnd._sourceNameLabel.Content = e.Item1.Title;
            wnd._statusLabel.Content = e.Item2;
            lock (_syncObject) {
                _stack.Add(wnd);
            }
            wnd.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;

            wnd.Top = 0;
            wnd.Left = 0;
            wnd.Focusable = false;
            wnd.Visibility = System.Windows.Visibility.Visible;
        }



        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = this;
            //Topmost = true;
            var p = PointFromScreen(new Point(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height));
            p.Y -= _stack.Count*Height;
            p.X -= Width;
            Left = p.X;
            Top = p.Y;
        }


    }
}
